package pe.gob.sunat.controller;

import javax.servlet.http.HttpServletRequest;

import net.tanesha.recaptcha.ReCaptcha;
import net.tanesha.recaptcha.ReCaptchaFactory;
import net.tanesha.recaptcha.ReCaptchaResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import pe.gob.sunat.util.Constantes;

@Controller
@RequestMapping("captcha/**")
public class CaptchaController {

	@Autowired
	private ReCaptcha reCaptcha;
	
	
	public String getHtmlCaptcha(){		
		ReCaptcha c = ReCaptchaFactory.newReCaptcha(Constantes.PUBLIC_KEY,
				Constantes.PRIVATE_KEY, false);	
		return c.createRecaptchaHtml(null, null);
	}

	
	@RequestMapping(value = "/captcha/index.html", method = RequestMethod.GET)
	public ModelAndView showInit() {

		ModelMap modelMap = new ModelMap();
		modelMap.put(Constantes.RECAPTCHA_HTML, getHtmlCaptcha());

		return new ModelAndView("captcha", modelMap);
	}

	@RequestMapping(value = "/captcha/validate")
	public ModelAndView validateCaptcha(HttpServletRequest request) {

		ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(
				request.getRemoteAddr(),
				request.getParameter("recaptcha_challenge_field"),
				request.getParameter("recaptcha_response_field"));

		Boolean valid = reCaptchaResponse.isValid();
		ModelMap modelMap = new ModelMap();

		if (!valid) {

			modelMap.put(Constantes.RECAPTCHA_HTML, getHtmlCaptcha());
			modelMap.put("TextError", "Ingrese los valores correctos");
		}
		modelMap.put("valid", valid);

		return new ModelAndView("captcha", modelMap);
	}

}
